package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.concurrent.CountDownLatch;

@SpringBootApplication
public class SpringbootRedisApplication {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringbootRedisApplication.class);

    // 消息侦听器容器 (连接工厂, 消息侦听器)
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory factory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        // 连接到redis服务器
        container.setConnectionFactory(factory);
        // 注册消息侦听器 (谢谢侦听器, 侦听主题)
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));

        return container;
    }

    /*
    消息侦听器适配器, 可以根据需要未消息处理方法命名
     */
    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        // (消息到达时调用的方法, 命名)
        return new MessageListenerAdapter(receiver, "reveiverMessage");
    }

    // Redis 消息接收器
    @Bean
    Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }

    @Bean
    CountDownLatch countDownLatch() {
        return new CountDownLatch(1);
    }

    // Redis 模板, 发送消息
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    public static void main(String[] args) throws InterruptedException {

        ApplicationContext ctx = SpringApplication.run(SpringbootRedisApplication.class, args);

        StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
        CountDownLatch latch = ctx.getBean(CountDownLatch.class);

        LOGGER.info("Sending message...");

        template.convertAndSend("chat", "Hello form redis");

        latch.wait();

        System.exit(0);

    }


}
